const DB = require('../../utils/db');

module.exports = {
	chatUserList: async (userId) => {
		// 查找用户列表
		let [list] = await DB.query(`select id ,username name,avatar from t_user where type =1 and id!=?`, [userId]);

		// 我跟谁聊过天/跟我聊过天
		let [ownList] = await DB.query(`select * from t_single_msg where fromId=? or toId=?`, [userId, userId]);
		let takeList = [];

		ownList.forEach((item) => {
			takeList.push(item.fromId);
			takeList.push(item.toId);
		});

		takeList = [...new Set(takeList)];

		// 聊过天的，展示最后一条消息
		for (let ele of list) {
			if (takeList.includes(ele.id)) {
				let [arr] = await DB.query(`select *,date_format(createTime,'%Y-%m-%d %H:%i:%s') createTime from t_single_msg where fromId=? or toId=? order by createTime desc limit 1`, [
					ele.id,
					ele.id
				]);

				ele.time = arr[0].createTime;
				ele.msg = decodeURIComponent(arr[0].msg);
				ele.mode = 1;
				ele.msgType = arr[0].msgType;
			} else {
				ele.time = 0;
				ele.msg = '未聊天';
				ele.mode = 1;
				ele.msgType = 1;
			}
		}

		list.sort((a, b) => {
			return new Date(b.time) - new Date(a.time);
		});

		// 查找群表(目前只有一个群)
		let [groupList] = await DB.query('select id ,name,avatar from t_grounp');
		let [groupMsgList] = await DB.query(`select *,date_format(createTime,'%Y-%m-%d %H:%i:%s') createTime from t_grounp_msg where grounpId=? order by createTime desc limit 1`, [groupList[0].id]);

		let newGoupList = groupList.map((p) => {
			return {
				...p,
				name: p.name + ` (${list.length + 1}人)`,
				time: (groupMsgList.length && groupMsgList[0].createTime) || 0,
				mode: 2, //1单人聊天 2 群聊
				msg: (groupMsgList.length && decodeURIComponent(groupMsgList[0].msg)) || '',
				msgType: (groupMsgList.length && groupMsgList[0].msgType) || 1 //1文字 2图片 3文件
			};
		});

		return [...newGoupList, ...list];
	},

	chatByIdList: async (mode, fromId, toId) => {
		if (mode === 1) {
			// 一对一

			let [list] = await DB.query(
				`select a.*, date_format(a.createTime,'%Y-%m-%d %H:%i:%s') createTime,u.username,u.avatar from (select * from t_single_msg where (fromId =? and toId=?) or (fromId =? and toId=?)) a
                        left join t_user u on u.id=a.fromId order by a.createTime asc`,
				[fromId, toId, toId, fromId]
			);

			return list;
		} else {
			// 群聊

			let [list] = await DB.query(
				`select g.*,date_format(g.createTime,'%Y-%m-%d %H:%i:%s') createTime,u.avatar,u.username name from t_grounp_msg g left join t_user u on g.fromId = u.id where g.grounpId=?`,
				[toId]
			);

			return list;
		}
	}
};
